
var mails = null;
var emptymessage = null;

// Performs the login
function verifyLogin(){
    var form = document.forms[0];
    sessionStorage.username = form.elements["email"].value;
    sessionStorage.password = form.elements["password"].value;
    var req = new XMLHttpRequest();
    var url = window.location.protocol + "//" + window.location.host + "/mail-browser/services/verify/";
    var params = sessionStorage.username+"/"+sessionStorage.password;
    req.open('GET', url+params, false);
    req.send(null);
    if(req.responseText === 'true')
        window.location.replace("home.html");
    else
      document.getElementById("err").innerHTML="The email account you have entered does not exist.. Please try again";
}

// Fetches all mails initially
function loadHome(){
    if(mails === null){
        document.getElementById("hname").innerHTML=sessionStorage.username;
        var req = new XMLHttpRequest();
        var url = window.location.protocol + "//" + window.location.host + "/mail-browser/services/getmails/";
        var params = sessionStorage.username+"/"+sessionStorage.password;
        req.open('GET', url+params, false);
        req.send(null);
        var xmlDoc = req.responseXML;
        updateMails(xmlDoc);
        updateHome();
    } else {
        updateHome();
    }
}

// Performs a search
function search(){
    document.getElementById("keyworderror").style.display = 'none';
    document.getElementById("optionserror").style.display = 'none';
    var kw = document.getElementById("keywordform").value;
    var sender_search = document.getElementById("senderbox").checked;
    var content_search = document.getElementById("contentbox").checked;
    var subject_search = document.getElementById("subjectbox").checked;
    var time_search = document.getElementById("timebox").checked;
    var from = document.getElementById("from").value;
    var to = document.getElementById("to").value;
    if(from === "" || !time_search)
        from = "null";
    if(to === "" || !time_search)
        to = "null";
    var req = new XMLHttpRequest();
    var url;
    var status = sender_search+content_search+subject_search+time_search;
    if((!time_search && kw === "") || (time_search && from === "null")){
        //alert("Please enter a valid keyword query");
        document.getElementById("keyworderror").style.display = 'block';
    }
    else {
        if(status === 0){
            //alert("Please choose at least one filtering method");
            document.getElementById("optionserror").style.display = 'block';
        } else {
            if(status > 1){
                url = window.location.protocol + "//" + window.location.host + "/mail-browser/services/multifilter/";
                req.open('GET', url+sender_search+"/"+content_search+"/"+subject_search+"/"+from+"/"+to+"/"+kw, false);
            } else {
               if(sender_search)
                   url = window.location.protocol + "//" + window.location.host + "/mail-browser/services/filterbysender/"+kw;
               if(content_search)
                   url = window.location.protocol + "//" + window.location.host + "/mail-browser/services/filterbycontent/"+kw;
               if(subject_search)
                   url = window.location.protocol + "//" + window.location.host + "/mail-browser/services/filterbysubject/"+kw;
               if(time_search)
                   url = window.location.protocol + "//" + window.location.host + "/mail-browser/services/filterafter/"+from;
                req.open('GET', url, false);
            }
            req.send(null);
            emptymessage="You have received no mails with the given keyword";
            var xmlDoc = req.responseXML;
            updateMails(xmlDoc);
            updateHome();
        }
    }
}

// Fetches all other mails resetting the filter
function resetFilter(){
    document.getElementById("keyworderror").style.display = 'none';
    document.getElementById("optionserror").style.display = 'none';
    document.getElementById("keywordform").value = "";
    document.getElementById("senderbox").checked = false;
    document.getElementById("contentbox").checked = false;
    document.getElementById("subjectbox").checked = false;
    document.getElementById("timebox").checked = false;
    document.getElementById("from").value = "";
    document.getElementById("to").value = "";
    var req = new XMLHttpRequest();
    var url = window.location.protocol + "//" + window.location.host + "/mail-browser/services/getall";
    req.open('GET', url, false);
    req.send(null);
    var xmlDoc = req.responseXML;
    updateMails(xmlDoc);
    updateHome();
}

// Updates the mails array from the xmlDoc
function updateMails(xmlDoc){
    mails = new Array();
    var x = xmlDoc.getElementsByTagName("from");
    for(i=0;i<x.length;i++){
        var mail = new Object();
        mail.from = xmlDoc.getElementsByTagName("from")[i].childNodes[0].nodeValue;
        mail.date = new Date(xmlDoc.getElementsByTagName("date")[i].childNodes[0].nodeValue).toLocaleDateString();
        mail.subject = xmlDoc.getElementsByTagName("subject")[i].childNodes[0].nodeValue;
        mail.content_overview = xmlDoc.getElementsByTagName("content_overview")[i].childNodes[0].nodeValue;
        mail.content = xmlDoc.getElementsByTagName("content")[i].childNodes[0].nodeValue;
        mails[i] = mail;
    }
}

// Refreshes the list of mails
function updateHome(){
    var content = "";
    if(mails.length === 0){
        if(emptymessage === null)
            document.getElementById("mails").innerHTML = "<div class='empty-message'> You have no mails in your folder </div>";
        else
            document.getElementById("mails").innerHTML = "<div class='empty-message'> "+emptymessage+"</div>";
    } else {
        var kw = document.getElementById("keywordform").value;
        var sender_search = document.getElementById("senderbox").checked;
        //var content_search = document.getElementById("contentbox").checked;
        var subject_search = document.getElementById("subjectbox").checked;
        for(i=0;i<mails.length;i++){
            content += '<div class="mail" onclick="showMail('+i+')">'
                +'<span class="from">'+highlightme(mails[i].from, kw, sender_search)
                +'</span><span class="date">'+mails[i].date
                +'</span><span class="subject">'+highlightme(mails[i].subject, kw, subject_search)
                +'</span><div class="content"><xmp>'+mails[i].content_overview
                +'</xmp></div></div>';
        }
        document.getElementById("mails").innerHTML = content;
    }
}

// Opens an overlay to read the full mail
function showMail(i){
    var overlay = document.createElement("div");
    overlay.setAttribute("id","overlay");
    overlay.setAttribute("class", "overlay");
    document.body.appendChild(overlay);

    var cmail = document.createElement("div");
    cmail.setAttribute("id","complete_mail");
    cmail.setAttribute("class","overlaying");
    //cmail.onclick=restore;
    
    var closebtn = "<input class='close-btn' type='image' src='close-icon.png' onclick='restore();' />";
    document.body.appendChild(cmail);
    var mail = mails[i];
    var kw = document.getElementById("keywordform").value;
    var sender_search = document.getElementById("senderbox").checked;
    //var content_search = document.getElementById("contentbox").checked;
    var subject_search = document.getElementById("subjectbox").checked;
   complete_mail_content = "<div><div class='fullitem'><div class='fulllabel'>From</div><div class='fullitemval'>"+highlightme(mail.from, kw, sender_search)+"</div></div>"
                            +"<div class='fullitem'><div class='fulllabel'>Subject</div><div class='fullitemval'>"+highlightme(mail.subject, kw, subject_search)+"</div></div>"
                            +"<div class='fullitem'><div class='fulllabel'>Date</div><div class='fullitemval'>"+mail.date+"</div></div>"
                            +"<xmp class='fullcontent'>"+mail.content+"</xmp>"
                            +"</span></div>";
   document.getElementById("complete_mail").innerHTML = closebtn + complete_mail_content;
}

// restore page to normal
function restore() {
    document.body.removeChild(document.getElementById("overlay"));
    document.body.removeChild(document.getElementById("complete_mail"));
}

function highlightme(text, highlight, status){
    if(text && status){
        text = text.replace(highlight, "<mark>"+highlight+"</mark>");
    }
    return text;
}
